package com.aiyi.education.admin.controller;


import cn.hutool.crypto.digest.BCrypt;
import com.aiyi.education.admin.service.IKsAdminService;
import com.aiyi.education.entity.KsUserWithBLOBs;
import com.aiyi.education.entity.admin.KsAdmin;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.education.annotation.Pass;
import com.education.annotation.ValidationParam;
import com.education.config.ResponseHelper;
import com.education.config.ResponseModel;
import com.education.util.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author renyong
 * @email sxgyry@163.com
 * @date
 */
@Slf4j
@RestController
@Api(tags = "管理员管理")
@RequestMapping("/ksAdmin")
public class KsAdminController {

    @Autowired
    private IKsAdminService ksAdminService;


    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<KsAdmin>> queryPageList(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<KsAdmin>> result = new Result<>();
        QueryWrapper<KsAdmin> queryWrapper = new QueryWrapper<>();
        Page<KsAdmin> page = new Page<>(pageNo, pageSize);
        IPage<KsAdmin> pageList = ksAdminService.page(page,queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        log.info(pageList.toString());
        return result;
    }

    /**
     * 添加管理员
     * @param ksAdmin
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @Pass
    public Result<KsAdmin>  addAdmin(@RequestBody KsAdmin ksAdmin){
        Result<KsAdmin> result = new Result<KsAdmin>();
        try{
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_name", ksAdmin.getUserName());
            List<KsAdmin> admins=ksAdminService.list(queryWrapper);
            if(admins!=null&&admins.size()>0){
                result.error500("用户名已经存在！");
                return result;
            }
            ksAdmin.setPassword(BCrypt.hashpw(ksAdmin.getPassword(), BCrypt.gensalt()));
            ksAdmin.setAddDate(new Date());
            ksAdminService.save(ksAdmin);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 删除管理员
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        ksAdminService.removeById(id);
        return Result.ok("删除管理员成功");
    }

    /**
     * 批量删除管理员
     */
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        ksAdminService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除管理员成功");
    }

    /**
     * 修改管理员
     * @param ksAdmin
     * @return
     */
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public Result<?> edit(@RequestBody KsAdmin ksAdmin){
        ksAdminService.updateById(ksAdmin);
        return Result.ok("管理员修改成功");
    }


    @ApiOperation(value="管理员注册", notes="body体参数,不需要Authorization",produces = "application/json")
    /*@ApiImplicitParams({
            @ApiImplicitParam(name = "requestJson", value = "{\"username\":\"\",\"mobile\":\"13888888888\",</br>" +
                    "\"captcha\":\"5780\",\"password\":\"123456\",</br>\"rePassword\":\"123456\",\"job\":\"java开发\"," +
                    "</br>\"unit(可不传)\":\"xxx公司\"}"
                    , required = true, dataType = "String",paramType="body")
    })*/
    @PostMapping("/admin_register")
    //@Log(action="register",modelName= "home_owner_login",description="注册接口")
    @Pass
    public ResponseModel<KsAdmin> register(//@ValidationParam("username,password,rePassword,mobile,captcha,job")
                                                   @RequestBody JSONObject requestJson)throws Exception {
        return ResponseHelper.buildResponseModel( ksAdminService.checkAndRegisterUser(requestJson));
    }

    @ApiOperation(value="管理员账号登录", notes="body体参数,不需要Authorization",produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "requestJson", value = "{\"mobile\":\"13888888888\",\"password\":\"123456\"}"
                    , required = true, dataType = "String",paramType="body")
    })
    @PostMapping("/admin_login")
    @Pass
    public ResponseModel<Map<String, Object>> login(
            @ValidationParam("userAccount,password")@RequestBody JSONObject requestJson) throws Exception{
        return ResponseHelper.buildResponseModel(ksAdminService.checkLoginAccountAndPasswd(requestJson));
    }

}
